package com.yunban.project.message.utils;


import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.yunban.project.message.domain.CSMessageManage;
import com.yunban.project.message.service.CSMessageManageService;
import jakarta.annotation.Resource;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import net.lab1024.sa.base.common.exception.BusinessException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author lijiajun
 */
@Slf4j
@Component
public class WorkNoticeSendUtils {

    private static final String BASE_URL = "https://tz.yunban.cn/cgi-bin/isv-api/";

    private static final String BASE_WX_MSG_URL = "https://tz.yunban.cn/cgi-bin/isv-api/send-notice?token=%s";

    private static final String APP_ID = "yunban_iot";

    private static final String SECRET = "yuhban_iot@2024";

    private static final String PID = "46";

    private static final String MANAGER = "2000012";

    @Value(value = "${work.notice.uri}")
    private String sourceUri;

    @Resource
    private RestTemplate restTemplate;

    @Resource
    private CSMessageManageService csMessageManageService;

    @SneakyThrows
    public String getToken() {
        String requestUrl = BASE_URL + "access-token?appId=" + APP_ID + "&appSecret=" + SECRET + "&pid=" + PID + "&manager=" + MANAGER + "&grantType=code";
        System.out.println(requestUrl);
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(requestUrl, String.class);

        if (responseEntity.getStatusCode().is2xxSuccessful()) {
            // 解析JSON响应并提取accessToken字段
            String responseBody = responseEntity.getBody();
            log.info("responseBody: {}", responseBody);
            JSONObject responseJson = JSON.parseObject(responseBody);
            if (ObjectUtils.isEmpty(responseJson)) {
                throw new BusinessException("获取accessToken失败");
            }
            if (Integer.parseInt(responseJson.get("status").toString()) == HttpStatus.OK.value()) {
                Object resultObject = responseJson.get("result");
                if (ObjectUtils.isEmpty(resultObject)) {
                    throw new BusinessException("获取accessToken失败");
                }
                JSONObject jsonObject = JSON.parseObject(resultObject.toString());
                if (!ObjectUtils.isEmpty(jsonObject)) {
                    return jsonObject.getString("accessToken");
                }
            }
            throw new BusinessException("获取accessToken失败");
        } else {
            throw new RuntimeException("获取访问令牌失败");
        }
    }

    public String httpPostJson(String url, Object data) {
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<Object> requestEntity = new HttpEntity<>(data, headers);

        ResponseEntity<String> responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);

        if (responseEntity.getStatusCode() == HttpStatus.OK) {
            return responseEntity.getBody();
        } else {
            throw new BusinessException("HTTP POST request failed with status code: " + responseEntity.getStatusCode());
        }
    }

    @Async
    public void sendWordNotice(String sessionId, String message) {
        Map<String, Object> noticeMap = new HashMap<>();
        // 获取接收人手机号
        List<CSMessageManage> list = csMessageManageService.list();
        // 使用stream获取 list 中的 phoneNos
        List<String> phoneNos = list.stream().map(CSMessageManage::getPhoneNo).toList();
        if (CollectionUtils.isEmpty(phoneNos)) {
            return;
        }
        String token = getToken();
        String requestUrl = String.format(BASE_WX_MSG_URL, token);
        noticeMap.put("phoneNos", phoneNos);
        noticeMap.put("title", "舆情官网客服消息通知");
        noticeMap.put("content", "有新的客服消息，请快去看看吧");
        LocalDateTime now = LocalDateTime.now();
        // now 转为 yyyy-MM-dd HH:mm:ss
        String startTime = now.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        noticeMap.put("startTime", startTime);
        noticeMap.put("sourceUri", sourceUri + "?sessionId=" + sessionId);
        httpPostJson(requestUrl, noticeMap);
    }
}
